class MyBlonkingQueue{
    private int[] data;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private Object locker = new Object();
    public MyBlonkingQueue(int capacity){
        data = new int[capacity];
    }

    //放入元素
    public void put(int elem) throws InterruptedException {
        synchronized(locker){
            if (size == data.length){
                locker.wait();
            }
            data[tail] = elem;
            locker.notify();
            size++;
            tail++;
            if (tail >= data.length){
                tail = 0;
            }
        }
    }
    //取出元素
    public int take() throws InterruptedException {
        synchronized(locker){
            if (size == 0){

                locker.wait();
            }
            int ret = data[head];
            size--;
            head++;
            locker.notify();
            if (head >= data.length){
                head = 0;
            }
            return ret;
        }
    }
}

public class Demo2 {
    public static void main(String[] args) {
        MyBlonkingQueue queue = new MyBlonkingQueue(10);
        Thread t1 = new Thread(()->{
            while (true){
                for (int i = 0; i < 10000; i++) {
                    try {
                        queue.put(i);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("生产了:"+i);
                }
            }
        });
        Thread t2 = new Thread(()->{
            while (true){
                int ret = 0;
                try {
                    ret = queue.take();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消费了:"+ret);
            }
        });
        t1.start();
        t2.start();
    }
}
